import { useEffect, useState } from 'react';
import axios from 'axios';
import { useTheme } from '../context/ThemeContext';
import DashboardLayout from '../components/DashboardLayout';
import AskFormView from '../components/AskFormView';
import ReplyFormView from '../components/ReplyFormView';
import ReplyFormEdit from '../components/ReplyFormEdit';
import TabButtons from '../components/TabButtons';
import { AskForm, ReplyForm } from '../types/forms';

const ReplyerDashboard: React.FC = () => {
    const { theme } = useTheme();
    const [askForms, setAskForms] = useState<AskForm[]>([]);
    const [myRepliedForms, setMyRepliedForms] = useState<AskForm[]>([]);
    const [selectedForm, setSelectedForm] = useState<AskForm | null>(null);
    const [activeTab, setActiveTab] = useState<'unanswered' | 'replied'>('unanswered');
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [currentUser, setCurrentUser] = useState('');
    const [currentUserId, setCurrentUserId] = useState('');
    const [isEditing, setIsEditing] = useState(false);
    const [editingReply, setEditingReply] = useState<Partial<ReplyForm>>({});
    const [newReply, setNewReply] = useState<Partial<ReplyForm>>({
        responder: '',
        responderUserId: '',
        company: '',
        responseContent: '',
        questionCategory: '',
        isClosed: false,
        remarks: ''
    });

    useEffect(() => {
        // 从localStorage获取用户信息
        const username = localStorage.getItem('username') || '';
        const userId = localStorage.getItem('userId') || '';
        setCurrentUser(username);
        setCurrentUserId(userId);
        setNewReply(prev => ({ 
            ...prev, 
            responder: username,
            responderUserId: userId
        }));
    }, []);

    useEffect(() => {
        const fetchForms = async () => {
            try {
                const token = localStorage.getItem('token');
                const [unansweredRes, allFormsRes] = await Promise.all([
                    axios.get('http://localhost:8000/api/askforms/unanswered', {
                        headers: { Authorization: `Bearer ${token}` },
                    }),
                    axios.get('http://localhost:8000/api/askforms', {
                        headers: { Authorization: `Bearer ${token}` },
                    })
                ]);

                // 设置未回复的表单
                setAskForms(unansweredRes.data);
                
                // 过滤出当前用户回复的表单
                const repliedForms = allFormsRes.data.filter((form: AskForm) => 
                    form.replies?.some(reply => reply.responder === currentUser)
                );
                setMyRepliedForms(repliedForms);
                
                setLoading(false);
            } catch (err) {
                setError('获取表单失败');
                setLoading(false);
            }
        };

        if (currentUser) {
            fetchForms();
        }
    }, [currentUser]);

    const handleSelectForm = (form: AskForm) => {
        setSelectedForm(form);
        setNewReply({
            ...newReply,
            company: form.company,
            questionCategory: form.department
        });
    };

    const handleSubmitReply = async () => {
        if (!selectedForm) return;
        if (!window.confirm('确定要提交这个回复吗？')) return;
        
        try {
            const token = localStorage.getItem('token');
            await axios.post('http://localhost:8000/api/replyforms', {
                ...newReply,
                askForm: { id: selectedForm.id }
            }, {
                headers: { Authorization: `Bearer ${token}` },
            });
            
            await refreshForms();
            setSelectedForm(null);
            setActiveTab('replied');
            setNewReply({
                ...newReply,
                responseContent: '',
                isClosed: false,
                remarks: ''
            });
        } catch (err) {
            setError('提交回复失败');
        }
    };

    const handleEditClick = () => {
        if (selectedForm?.replies?.[0]) {
            setEditingReply({
                ...selectedForm.replies[0],
                askForm: selectedForm
            });
            setIsEditing(true);
        }
    };

    const handleCancelEdit = () => {
        setIsEditing(false);
        setEditingReply({});
    };

    const handleUpdateReply = async () => {
        if (!selectedForm?.replies?.[0]) return;
        if (!window.confirm('确定要更新这个回复吗？')) return;
        
        try {
            const token = localStorage.getItem('token');
            await axios.patch(`http://localhost:8000/api/replyforms/${selectedForm.replies[0].id}`, editingReply, {
                headers: { Authorization: `Bearer ${token}` },
            });
            
            await refreshForms();
            const updatedForm = await fetchFormById(selectedForm.id);
            setSelectedForm(updatedForm);
            setIsEditing(false);
            setEditingReply({});
        } catch (err) {
            setError('更新回复失败');
        }
    };

    const handleDeleteReply = async () => {
        if (!selectedForm?.replies?.[0]) return;
        if (!window.confirm('确定要删除这个回复吗？删除后该问题将变为未回复状态。')) return;
        
        try {
            const token = localStorage.getItem('token');
            await axios.delete(`http://localhost:8000/api/replyforms/${selectedForm.replies[0].id}`, {
                headers: { Authorization: `Bearer ${token}` },
            });
            
            await refreshForms();
            setSelectedForm(null);
            setActiveTab('unanswered');
        } catch (err) {
            setError('删除回复失败');
        }
    };

    const refreshForms = async () => {
        const token = localStorage.getItem('token');
        const [unansweredRes, allFormsRes] = await Promise.all([
            axios.get('http://localhost:8000/api/askforms/unanswered', {
                headers: { Authorization: `Bearer ${token}` },
            }),
            axios.get('http://localhost:8000/api/askforms', {
                headers: { Authorization: `Bearer ${token}` },
            })
        ]);

        setAskForms(unansweredRes.data);
        const repliedForms = allFormsRes.data.filter((form: AskForm) => 
            form.replies?.some(reply => reply.responder === currentUser)
        );
        setMyRepliedForms(repliedForms);
    };

    const fetchFormById = async (id: number): Promise<AskForm> => {
        const token = localStorage.getItem('token');
        const response = await axios.get(`http://localhost:8000/api/askforms/${id}`, {
            headers: { Authorization: `Bearer ${token}` },
        });
        return response.data;
    };

    const renderFormList = (forms: AskForm[]) => (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
            {forms.map((form) => (
                <div
                    key={form.id}
                    onClick={() => handleSelectForm(form)}
                    style={{
                        padding: '15px',
                        border: '1px solid #ddd',
                        borderRadius: '4px',
                        cursor: 'pointer',
                        backgroundColor: selectedForm?.id === form.id 
                            ? (theme === 'light' ? '#e3f2fd' : '#2c3e50')
                            : (theme === 'light' ? 'white' : '#495057'),
                    }}
                >
                    <div style={{ fontWeight: 'bold', marginBottom: '5px' }}>
                        {form.department} - {form.position}
                    </div>
                    <div style={{
                        fontSize: '0.9em',
                        color: theme === 'light' ? '#666' : '#ccc',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                    }}>
                        {form.question}
                    </div>
                    {form.replies && form.replies[0] && (
                        <div style={{
                            fontSize: '0.8em',
                            color: theme === 'light' ? '#888' : '#aaa',
                            marginTop: '5px'
                        }}>
                            回复时间: {new Date(form.replies[0].createdAt).toLocaleString()}
                        </div>
                    )}
                </div>
            ))}
        </div>
    );

    const sidebarContent = (
        <>
            <h2 style={{ marginBottom: '20px' }}>回复管理</h2>
            <TabButtons
                options={[
                    { key: 'unanswered', label: '待回复', count: askForms.length },
                    { key: 'replied', label: '已回复', count: myRepliedForms.length }
                ]}
                activeTab={activeTab}
                onChange={(key) => setActiveTab(key as 'unanswered' | 'replied')}
            />
            {loading ? (
                <p>加载中...</p>
            ) : error ? (
                <p style={{ color: 'red' }}>{error}</p>
            ) : (
                renderFormList(activeTab === 'unanswered' ? askForms : myRepliedForms)
            )}
        </>
    );

    const mainContent = selectedForm ? (
        <div style={{ maxWidth: '800px', margin: '0 auto' }}>
            <h2 style={{ marginBottom: '30px' }}>问题详情</h2>
            <div style={{
                backgroundColor: theme === 'light' ? 'white' : '#495057',
                padding: '20px',
                borderRadius: '8px',
                boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
            }}>
                <AskFormView form={selectedForm} />

                {selectedForm.replies && selectedForm.replies[0] ? (
                    isEditing ? (
                        <ReplyFormEdit
                            reply={editingReply}
                            onChange={setEditingReply}
                            onSubmit={handleUpdateReply}
                            onCancel={handleCancelEdit}
                            submitLabel="更新"
                        />
                    ) : (
                        <ReplyFormView
                            reply={selectedForm.replies[0]}
                            onEdit={handleEditClick}
                            onDelete={handleDeleteReply}
                            canEdit={selectedForm.replies[0].responder === currentUser}
                        />
                    )
                ) : (
                    <ReplyFormEdit
                        reply={newReply}
                        onChange={setNewReply}
                        onSubmit={handleSubmitReply}
                        submitLabel="提交回复"
                    />
                )}
            </div>
        </div>
    ) : (
        <div style={{
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: theme === 'light' ? '#666' : '#ccc'
        }}>
            <p>请选择左侧的问题查看详情</p>
        </div>
    );

    return (
        <DashboardLayout sidebarContent={sidebarContent}>
            {mainContent}
        </DashboardLayout>
    );
};

export default ReplyerDashboard; 